<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            background-color: black;
        }
        .container{
            border:2px solid #dddddd;
            height: 400px;
            overflow: auto;
        }
    </style>
</head>
<body>
<div style="width: 750px;margin: 0 auto;background-color: #dddddd">
    <h1 style="background-color: lawngreen">1024聊天室</h1>
    <div class="container"></div>
    <div class="input">
        <input class="name" style="width: 50px;height: 15px;" type="text" value="游客">
        <input type="text" id="txt">
        <input type="button" id="btn" value="发送" onclick="sendMessage()">
        <input type="button" id="close" value="关闭连接" onclick="closeConn()"/>
    </div>
     <div id="content"></div>
</div>
<script src="/static/jquery-2.1.4.min.js"></script>
<script>
    $(function () {
            wsUpdater.start();
        });

    var wsUpdater = {
            socket: null,
            name: null,
            start: function() {
                var url = "ws://127.0.0.1:8888/chat";
                wsUpdater.socket = new WebSocket(url);
                wsUpdater.socket.onopen = function () {
                /* 与服务器端连接成功后，自动执行 */
                var newTag = document.createElement('div');
                newTag.innerHTML = "【连接成功】";
                document.getElementById('content').appendChild(newTag);
            };
                wsUpdater.socket.onmessage = function(event) {
                    console.log(event);
                    if(wsUpdater.name){
                        wsUpdater.showMessage(event.data);
                    }else{
                        wsUpdater.name = event.data;
                    }
                }
            },
            showMessage: function(content) {
                $('.container').append(content);
            }
        };

    function closeConn() {
        /* 服务器端主动断开连接时，自动执行 */
        if (confirm("您确定要关闭本页吗？")){
            // 旧方法
            {#window.opener=null;#}
            {#window.open('','_self');#}
            {#window.close();#}
            // 新方法
            window.location.href="about:blank";
            window.close();
            }
            else{}
        };
    $("#txt").keydown(function (e) {//当按下按键时
        if (e.which == 13) {//.which属性判断按下的是哪个键，回车键的键位序号为13
            $('#btn').trigger("click");//触发搜索按钮的点击事件
        }
    });

    function sendMessage() {
        var msg = {
            name:$(".name").val(),
            message: $("#txt").val()
        };
        wsUpdater.socket.send(JSON.stringify(msg));
    }

</script>
</body>
</html>